/*
 * Utility.java
 *
 * Created on 4 de Dezembro de 2007, 10:20
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package utility;

import java.applet.Applet;
import java.awt.*;
import java.awt.image.ImageProducer;
import java.io.*;
import java.net.URL;
import java.util.ResourceBundle;

/**
 *
 * @author rafaelbuck
 */
public class Utility
{

    public static Image loadImage(String path)
    {
        return loadImage(path, preparer);
    }

    public static Image loadImage(String path, Component renderer)
    {
        if(resourceDir != null)
            path = resourceDir + path;
        return (new Utility()).loadAnImage(path, renderer);
    }

    private Image loadAnImage(String path, Component renderer)
    {
        Image img = null;
        try
        {
            URL url = null;
            try
            {
                url = getClass().getResource(path);
            }
            catch(Exception _ex) { }
            if(url == null)
                if(applet != null)
                    url = new URL(applet.getCodeBase(), path);
                else
                    return null;
            if(applet != null)
            {
                System.out.println("url=" + url);
                try
                {
                    img = applet.getImage(url);
                }
                catch(Exception _ex) { }
                if(img == null)
                {
                    url = new URL(applet.getCodeBase(), path);
                    img = applet.getImage(url);
                }
            } else
            {
                img = Toolkit.getDefaultToolkit().createImage((ImageProducer)url.getContent());
            }
        }
        catch(Exception x)
        {
            System.out.println("Exception: " + x.getMessage() + ", " + x);
        }
        if(img != null)
            renderer.prepareImage(img, null);
        return img;
    }

    public static InputStream getInputStream(String path, Object obj)
    {
        InputStream is = null;
        try
        {
            try
            {
                is = obj.getClass().getResourceAsStream(path);
            }
            catch(Exception _ex) { }
            if(is == null && applet != null)
            {
                URL url = new URL(applet.getCodeBase(), path);
                is = url.openStream();
            }
        }
        catch(Exception _ex) { }
        return is;
    }

    public static String loadText(String path)
    {
        if(resourceDir != null)
            path = resourceDir + path;
        return (new Utility()).loadAText(path);
    }

    private String loadAText(String path)
    {
        String txt = "";
        try
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream(path, this)));
            String line;
            while((line = reader.readLine()) != null) 
                txt = txt + line + "\n";
            reader.close();
        }
        catch(Exception _ex) { }
        return txt;
    }

    public static boolean areWeOnDOS()
    {
        return weAreOnDOS;
    }

    public static void setResourceDir(String dir)
    {
        resourceDir = dir;
    }

    public static String compileString(String tag, String args[], ResourceBundle res)
    {
        String format = res.getString(tag);
        StringBuffer ret = new StringBuffer(format.length());
        for(int i = 0; i < format.length(); i++)
        {
            char c = format.charAt(i);
            if(c == '%' || c == '@')
            {
                int argNum = -1;
                if(i < format.length() - 1)
                    switch(format.charAt(i + 1))
                    {
                    default:
                        break;

                    case 37: // '%'
                        if(c == '%')
                        {
                            ret.append('%');
                            i++;
                        }
                        break;

                    case 64: // '@'
                        if(c == '@')
                        {
                            ret.append("@");
                            i++;
                        }
                        break;

                    case 48: // '0'
                        argNum = 0;
                        break;

                    case 49: // '1'
                        argNum = 1;
                        break;

                    case 50: // '2'
                        argNum = 2;
                        break;

                    case 51: // '3'
                        argNum = 3;
                        break;

                    case 52: // '4'
                        argNum = 4;
                        break;

                    case 53: // '5'
                        argNum = 5;
                        break;

                    case 54: // '6'
                        argNum = 6;
                        break;

                    case 55: // '7'
                        argNum = 7;
                        break;

                    case 56: // '8'
                        argNum = 8;
                        break;

                    case 57: // '9'
                        argNum = 9;
                        break;
                    }
                if(argNum >= 0 && argNum < args.length)
                {
                    if(c == '%')
                        ret.append(args[argNum]);
                    else
                        ret.append(res.getString(args[argNum]));
                    i++;
                }
            } else
            {
                ret.append(c);
            }
        }

        return new String(ret);
    }

    public static Frame getFrame(Component comp)
    {
        for(; comp != null; comp = comp.getParent())
            if(comp instanceof Frame)
                return (Frame)comp;

        return new Frame();
    }

    public static boolean equalBytes(byte arr1[], int off1, byte arr2[], int off2, int len)
    {
        while(len-- > 0) 
            if(arr1[off1++] != arr2[off2++])
                return false;
        return true;
    }

    public static void setApplet(Applet applet)
    {
        applet = applet;
    }

    public static boolean areWeInAnApplet()
    {
        return applet != null;
    }

    public static String getProperty(String prop)
    {
        if(areWeInAnApplet())
            return applet.getParameter(prop);
        try
        {
            return System.getProperty(prop);
        }
        catch(Throwable _ex)
        {
            return null;
        }
    }

    public static int getIntProperty(String propertyName, int defaultValue)
    {
        int ret = defaultValue;
        String pr = getProperty(propertyName);
        if(pr != null)
            try
            {
                ret = Integer.parseInt(pr);
            }
            catch(Exception _ex) { }
        return ret;
    }

    public static boolean getBooleanProperty(String propertyName, boolean defaultValue)
    {
        boolean ret = defaultValue;
        String pr = getProperty(propertyName);
        if(pr != null)
            try
            {
                ret = Boolean.getBoolean(pr);
            }
            catch(Exception _ex) { }
        return ret;
    }

    /** Creates a new instance of Utility */
    public Utility()
    {
    }

    private static Component preparer = new Canvas();
    private static boolean weAreOnDOS;
    private static String resourceDir = "resources/";
    private static Applet applet;

    static 
    {
        weAreOnDOS = File.separatorChar == '\\';
    }
}